﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace BomberManServer.Threading
{
    // a pool to store the threads so we dont have to create another one if one is available
    class ThreadedSocketPool
    {
        // the max threads we are allowed to create
        int max;
        // the first port number that will be assigned
        int portBase;
        // storage for the threads that are waiting
        List<ThreadedSocket> waiting;
        // storage for the threads that are working
        List<ThreadedSocket> working;

        public ThreadedSocketPool(int portBase, int max) {
            this.portBase = portBase;
            this.max = max;
            waiting = new List<ThreadedSocket>();
            working = new List<ThreadedSocket>();
        }

        // returns true if threads are available
        public bool isBusy()
        {
            return (working.Count == max);
        }

        // grabbing a thread from the pool
        // we assume you already called isBusy() before
        public ThreadedSocket grab() {
            ThreadedSocket thread;
            // threads waiting
            if (waiting.Count == 0)
                thread = new ThreadedSocket(portBase + working.Count);
            else
            {
                thread = waiting[0];
                waiting.RemoveAt(0);
            }

            working.Add(thread);
            return thread;
        }

        // set the waiting thread available
        public void release(ThreadedSocket thread)
        {
            waiting.Add(thread);
            working.Remove(thread);
        }
    }
}
